<template>
  <div class="app-container customer-div" style="overflow-x: auto">
    <el-form :inline="true"  :model="listQuery" size="mini" label-width="50px">
       <div>
         <el-radio-group v-model="listQuery.analysisType" size="small" @change="changeType" style="margin-top:10px;">
           <el-radio-button label="month">按月</el-radio-button>
           <el-radio-button label="quarter">按季</el-radio-button>
           <el-radio-button label="half">半年</el-radio-button>
           <el-radio-button label="year">按年</el-radio-button>
         </el-radio-group>
       </div>
          <el-form-item label="日期：" style="margin-top:20px;">
            <el-date-picker
              :clearable="false"
              v-if="listQuery.analysisType != 'half'"
              :format="dataFormat"
              :value-format="dataFormat"
              v-model="listQuery.createDate"
              :type="dataType"
              align="center"
              unlink-panels
              range-separator="~"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              class="date-class"
              prefix-icon="calendar-icon"
            >
            </el-date-picker>
            <halfyearPicker
              v-else
              width="300"
              ref="statisticPicker3"
              @updateTimeRange="updateStatisticYear">
            </halfyearPicker>
          </el-form-item>
          <el-form-item style="margin-top:20px;">
            <el-button
              style="margin-left:10px;"
              @click="handleSearchList"
              type="primary">
              查询
            </el-button>
          </el-form-item>
        </el-form>
       <el-checkbox-group v-model="labelList" @change="changeList">
           <el-checkbox label="y1">销售金额</el-checkbox>
           <el-checkbox label="y2">销售成本</el-checkbox>
           <el-checkbox label="y3">销售数量</el-checkbox>
           <el-checkbox label="y4">毛利</el-checkbox>
           <el-checkbox label="y5">毛利率</el-checkbox>
           <el-checkbox label="y6">同比</el-checkbox>
           <el-checkbox label="y7">结算毛利</el-checkbox>
           <el-checkbox label="y8">采购毛利</el-checkbox>
           <el-checkbox label="y9">销售发货毛利</el-checkbox>
           <el-checkbox label="y10">运费</el-checkbox>
       </el-checkbox-group>

       <div id="myChart" style="height:400px;margin-top:20px" ></div>
        <!--数据列表-->
        <div class="table-container">
          <el-table
            ref="multipleTable"
            v-loading="listLoading"
            :data="tableData"
            border
            style="width: 100%; margin-top: 20px">
            <el-table-column  label="时间"  align="center" min-width="100">
              <template slot-scope="scope">
                {{scope.row.time}}
              </template>
            </el-table-column>
            <el-table-column align="center" label="销售数量" min-width="100">
              <template slot-scope="scope">
                {{scope.row.num | fifnum}}
              </template>
            </el-table-column>
            <el-table-column label="销售金额" align="center" min-width="150">
              <template slot-scope="scope">
                {{scope.row.sale | fifnum}}
              </template>
            </el-table-column>
            <el-table-column min-width="100" label="销售成本" align="center">
              <template slot-scope="scope">
                {{scope.row.purchase | fifnum}}
              </template>
            </el-table-column>
            <el-table-column min-width="100" label="毛利" align="center">
              <template slot-scope="scope">
                {{scope.row.profit | fifnum}}
              </template>
            </el-table-column>
            <el-table-column min-width="100" label="毛利率" align="center">
              <template slot-scope="scope">
                {{scope.row.profitRate}}%
              </template>
            </el-table-column>
            <el-table-column min-width="100" label="结算毛利" align="center">
              <template slot-scope="scope">
                  {{scope.row.settle | fifnum}}
              </template>
            </el-table-column>
            <el-table-column min-width="100" label="采购毛利" align="center">
              <template slot-scope="scope">
                {{scope.row.purchaseP | fifnum }}
              </template>
            </el-table-column>
            <el-table-column min-width="100" label="销售发货毛利" align="center">
              <template slot-scope="scope">
                {{scope.row.saleP | fifnum}}
              </template>
            </el-table-column>
            <el-table-column min-width="100" label="运费" align="center">
              <template slot-scope="scope">
                {{scope.row.freight | fifnum}}
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination-container">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            layout="total, sizes,prev, pager, next,jumper"
            :current-page.sync="listQuery.pageNum"
            :page-size="listQuery.pageSize"
            :page-sizes="[10,15,20,50,100]"
            :total="count">
          </el-pagination>
        </div>

  </div>
</template>

<script>
const defaultListQuery={
  analysisType:'month',
  "createDate" : null,  //时间
  "pageNum"    : 1,
  "pageSize"   : 10
};

import {developTopSaleByCustomer ,financechart ,financechartList} from '@/api/company'
import halfyearPicker from '@/views/components/halfyearPicker'
import {formatDate} from '@/utils/date';
import {numberToCurrencyNo} from '@/utils/index'
import store from '@/store'
import { mapGetters } from 'vuex'

export default {
  name: "saleReport",
  data(){
    return{
      listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
      tableData: [],
      count: 0,
      listLoading: false,
      roles:store.getters.roles ? store.getters.roles : [],
      userOptionList:[],
      dataType:'monthrange',
      dataFormat:'yyyy-MM',
      labelName: {y1:'销售金额',y2:'销售成本',y3:'销售数量',y4:'毛利',y5:'毛利率',y7:'结算毛利',y8:'采购毛利',y9:'销售发货毛利',y10:'运费'},
      echartsColor: {y1:'#546fc6',y2:'#91cd76',y3:'#fac958',y4:'#ef6667',y5:'#71c1df',y7:'#3ba272',y8:'#fc8452',y9:'#9a60b4',y10:'#7583af'},
      labelList:['y1','y2','y6'],
      echartsData:{},
      year:'',
      month:'',
    }
  },
  components : {halfyearPicker},
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),

  },
  created() {
    this.year = new Date().getFullYear();
    this.month = new Date().getMonth();
    let sMonth = this.month - 1 == -1 ? 12 : this.month;
    sMonth = sMonth < 10 ? '0'+sMonth :sMonth
    this.listQuery.createDate = [this.year+'-'+sMonth,this.year+'-'+sMonth]
    this.getList()
    this.getChartList()
  },
  filters: {
     fifnum(val){
       if(val){
         return numberToCurrencyNo(val)
       }else{
         return ''
       }

     }
  },
  methods:{
    changeList(){
       this.getChartList();
    },
    changeType(){
       this.listQuery.createDate = null;
       if(this.listQuery.analysisType == 'month'){
           this.dataType = 'monthrange'
           this.dataFormat = 'yyyy-MM';
           let sMonth = this.month - 1 == -1 ? 12 : this.month;
           sMonth = sMonth < 10 ? '0'+sMonth :sMonth
           this.listQuery.createDate = [this.year+'-'+sMonth,this.year+'-'+sMonth]
       }else if(this.listQuery.analysisType == 'quarter'){
           this.dataType = 'quarterrange'
           this.dataFormat = 'yyyy年 第Q季度'
           let q = '';
           if(this.month < 3){
             q = 1
           }else if(this.month < 6){
             q = 2
           }else if(this.month < 10){
             q = 3
           }else{
             q = 4
           }
          this.listQuery.createDate = [this.year+'年'+' '+'第'+q+'季度',this.year+'年'+' '+'第'+q+'季度']
       }else if(this.listQuery.analysisType == 'half'){
         this.dataType = 'halfrange'
         let h = '上'
         if(this.month > 6){
           h = '下'
         }
         this.listQuery.createDate = [this.year+' '+ h +'半年',this.year+' '+ h +'半年']
         this.$refs.statisticPicker3.setYear(this.year+' '+ h +'半年',this.year+' '+ h +'半年')
       }else if(this.listQuery.analysisType == 'year'){
         this.dataType = 'yearrange'
         this.dataFormat = 'yyyy'
         this.listQuery.createDate = [this.year+'',this.year+'']
       }
       this.handleSearchList()
    },

    updateStatisticYear(val){
      this.listQuery.createDate = val
    },

    //获取图表数据
    getChartList(){
      financechart(this.listQuery).then((res)=>{
        this.echartsData = res
        this.draw1()
      })
    },

    //画产品销量排行
    draw1(){
      let myChart = this.$echarts.init(document.getElementById('myChart'));
      let series = [];
      let legend = [];
      let keyList = JSON.parse(JSON.stringify(this.labelList));
      let isTb = keyList.indexOf('y6');
      if(isTb != -1){
        keyList.splice(isTb, 1);
      }
      let bamNum = this.echartsData.x.length * keyList.length;
      let showZoom = false;
      if(isTb != -1){
        bamNum = bamNum * 2
      }
      showZoom = bamNum > 12;
      let endnum =  100;
      endnum = 100 - parseInt(bamNum/12 * 10)
      endnum = endnum < 1 ? 1 : endnum
      console.log("endnum",endnum)
      let datalist = [];
      keyList.forEach((key)=>{
          let barObj = {
            name: this.labelName[key],
            data: this.echartsData['data'][key],
            type: 'bar',

            barMinWidth:50,
            barMaxWidth:50,
            color: this.echartsColor[key],
            label: {
              show: true,
              position: 'top',
              formatter:(params) => {
                let yIndex = params.seriesName.indexOf('金额');
                let y2Index = params.seriesName.indexOf('成本');
                let wIndex = params.seriesName.indexOf('毛利');
                let w2Index = params.seriesName.indexOf('运费');
                let showNum = ''
                let num
                if(yIndex != -1 || y2Index != -1){
                  num = params.value / 100000000
                  showNum = (parseInt(num * 100 ) / 100 ).toFixed(2) + '亿'
                }else if( wIndex != -1 || w2Index != -1){
                  if(params.seriesName != '毛利率'){
                    num = params.value / 10000
                    showNum = (parseInt(num * 100 ) / 100 ).toFixed(2) + '万'
                  }
                }
                return  showNum
              },

            },};
          let lineObj = {name: this.labelName[key], data: this.echartsData['data'][key], type: 'line', color: this.echartsColor[key],yAxisIndex: 1,}
          let seriesObj = this.labelName[key] != '销售数量' ? barObj: lineObj;
          series.push(seriesObj);
          legend.push(this.labelName[key]);
          datalist = datalist.concat(this.echartsData['data'][key])
          if(isTb != -1){
            let seriesObj2 = JSON.parse(JSON.stringify(seriesObj));
            seriesObj2.name = '同比' + this.labelName[key];
            seriesObj2.data =  this.echartsData['data2'][key],
            seriesObj2.color = 'red'
            seriesObj2.label= {
              show: true,
                position: 'top',
                formatter:(params) => {
                let yIndex = params.seriesName.indexOf('金额');
                let y2Index = params.seriesName.indexOf('成本');
                let wIndex = params.seriesName.indexOf('毛利');
                let w2Index = params.seriesName.indexOf('运费');
                let showNum = ''
                let num
                if(yIndex != -1 || y2Index != -1){
                  num = params.value / 100000000
                  showNum = (parseInt(num * 100 ) / 100 ).toFixed(2) + '亿'
                }else if( wIndex != -1 || w2Index != -1){
                  if(params.seriesName != '同比毛利率'){
                    num = params.value / 10000
                    showNum = (parseInt(num * 100 ) / 100 ).toFixed(2) + '万'
                  }
                }
                return  showNum
              },
            }
            series.push(seriesObj2);
            legend.push('同比' + this.labelName[key])
            datalist = datalist.concat(this.echartsData['data2'][key])
          }
      });

      let minList =  datalist.sort((a,b) => {
                    return a-b
                  })
      let min = minList[0];
      let max = minList[minList.length-1];
      let interval = (max - min) / this.echartsData.x.length
      min = (min - interval) < 0 ? 0 : min - interval
      max = max + interval
      // 绘制图表
      myChart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function (params, ticket, callback) {
            //x轴名称
            var name = params[0].name
            var html = ''
            params.forEach((el)=>{
              //图表title名称
              var seriesName = el.seriesName
              //值
              var value = el.value
              var valueFliter = numberToCurrencyNo(value)
              var dian = '<div style="width:10px;height:10px;border-radius: 50%;margin-right:5px;display:inline-block;background: '+ el.color +'"></div>'
              html = html + '<br />' + dian + seriesName +'：' + valueFliter
            })
            return name + html
          },
        },
        grid:{
          top: '50px',
          left: '20px',
          right: '40px',
          bottom: '50px',
          containLabel: true,
        },
        dataZoom : [
          {
            type: 'slider',
            realtime: true,
            start: 0,
            end: endnum,  // 数据窗口范围的结束百分比。范围是：0 ~ 100。
            show: showZoom,  // 是否展示
            handleSize: 0,      //两边手柄尺寸
            showDetail: false, //拖拽时是否展示滚动条两侧的文字
            zoomLock: false,         //是否只平移不缩放
            moveOnMouseMove: true, //鼠标移动能触发数据窗口平移
          }
        ],
        legend: {
          data:legend ,
        },
        xAxis: {
          type: 'category',
          data: this.echartsData.x
        },
        yAxis: [{
          type: 'value',
          axisLabel: {
            formatter: function (value, index) {
              return numberToCurrencyNo(value)
            },
          },

          // max:max,
          // min:min,
          // interval:interval
        },
          {
            type: 'value',
            name: '销售数量',
            position: 'right',
            alignTicks: true,
            axisLabel: {
              formatter: function (value, index) {
                return numberToCurrencyNo(value)
              },
            },
          },

        ],
        series: series
      },true);
    },

    handleSizeChange(val){
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val){
      this.listQuery.pageNum = val;
      this.getList();
    },

    handleSearchList(){
      this.listQuery.pageNum = 1;
      this.getList();
      this.getChartList()
    },

    //获取列表
    getList() {
      this.listLoading = true;
      financechartList(this.listQuery).then(response => {
        this.tableData = response.list;
        this.count = response.count;
        this.listLoading = false;
      }).catch(()=>{
        this.listLoading = false;
      });
    },



  },
}
</script>

<style scoped lang="scss">

</style>
